#pragma once
#include <iostream>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

const static uint16_t gport = 8888;
const static int glistensockfd = -1;
const static int gblcklog = 8;

using command_server_t = std::function<void(int sockfd,InetAddr addr)>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

class TcpServer
{
    class ThreadData
    {
    public:
        int _sockfd;
        TcpServer *_self;
        InetAddr _addr;

        ThreadData(int sockfd, TcpServer *self, InetAddr addr) : _sockfd(sockfd), _self(self), _addr(addr) {}
    };

public:
    TcpServer(command_server_t service, uint16_t port = gport) : _service(service),_port(port), _listensockfd(glistensockfd), _isrunning(false) {}

    void InitServer()
    {
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(FATAL, "scoket create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success,sockfd:%d\n", _listensockfd);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_listensockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success\n");

        if (listen(_listensockfd, gblcklog) < 0)
        {
            LOG(FATAL, "listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "lisen success\n");
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            int sockfd = accept(_listensockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                LOG(FATAL, "accept error\n");
                continue;
            }
            InetAddr addr(client);

            //version3 多线程版
             pthread_t tid;
             ThreadData *td=new ThreadData(sockfd,this,addr);
             pthread_create(&tid,nullptr,Excute,td);
        }
        _isrunning = false;
    }

    static void *Excute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->_service(td->_sockfd, td->_addr);
        delete td;
        return nullptr;
    }

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;
    command_server_t _service;
};